package com.ror.java.se.io;

//把assets/io/zip/a/目录打包成一个压缩包

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Demo14Zip {
    public static void main(String[] args) throws IOException {
        File src = new File("assets/io/zip/a/");
        File dest = new File("assets/io/zip/a-java.zip");
        zip(src, dest);
    }

    private static void zip(File src, File dest) throws IOException {
        if (src == null || dest == null) return;
        long before = System.currentTimeMillis();
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));
        putZipEntries(src, src.getName(), zos);
        long delta = System.currentTimeMillis() - before;
        System.out.println("took " + delta + "ms.");
    }

    private static void putZipEntries(File src, String srcPathInZip, ZipOutputStream zos) throws IOException {
        zos.putNextEntry(new ZipEntry(srcPathInZip));
        System.out.println("put " + srcPathInZip); //log
        if (src.isFile()) {
            FileInputStream fis = new FileInputStream(src);
            int len;
            byte[] bb = new byte[1024];
            while ((len = fis.read(bb)) != -1) {
                zos.write(bb, 0, len);
            }
            fis.close();
        } else { //src is dir
            File[] children = src.listFiles();
            if (children == null || children.length == 0) {
                zos.closeEntry();
                return;
            }
            for (File child : children) {
                putZipEntries(child, srcPathInZip + File.separator + child.getName(), zos);
            }
        }
        zos.closeEntry();
    }
}
